package com.sky.service.impl;

import com.sky.entity.OrderSum;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;

import com.sky.webSocket.WebSocketServer;

import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServicelmpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 销售额统计
     *
     * @param begin
     * @param end*
     * @return
     */
    @Override
    public TurnoverReportVO Turnover(LocalDate begin, LocalDate end) {
        //处理TurnoverReportVO中的dateList数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //处理TurnoverReportVO中的turnoverList数据
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate dateTime : dateList) {
            Map map = new HashMap();
            map.put("orderTime", dateTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.Turnover(map);
            //处理空值
            turnover = turnover == null ? 0.00 : turnover;
            turnoverList.add(turnover);
        }


        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .turnoverList(StringUtil.join(",", turnoverList))
                .build();


        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //处理UserReportVO中的dateList数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> allUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            Integer newCount = userMapper.selectNewUser(localDate);

            Integer allCount = userMapper.selectAllUser(localDate);

            newUserList.add(newCount);
            allUserList.add(allCount);

        }


        final UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .newUserList(StringUtil.join(",", newUserList))
                .totalUserList(StringUtil.join(",", allUserList))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        //处理OrderReportVO中的dateList数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            Integer validOrder = orderMapper.getOrderStatistics(date, Orders.COMPLETED);
            Integer orderCount = orderMapper.getOrderStatistics(date, null);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.00;
        if (validOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .orderCountList(StringUtil.join(",", orderCountList))
                .validOrderCountList(StringUtil.join(",", validOrderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    /**
     * 销量排名统计
     * @param begin
     * @param end
     * @return
     */

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
//        //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
//        private String nameList;
//
//        //销量列表，以逗号分隔，例如：260,215,200
//        private String numberList;
        //1.查询在这段时间内的orderId
        List<Long> orderIdList=orderMapper.selectOrderIdBytime(begin,end,Orders.COMPLETED);

       //2.通过得到的orderidlist  查询orderdetails
         List<String> nameList = new ArrayList();
         List<Integer> numberList = new ArrayList();


          List<OrderSum> orderSumList= orderDetailMapper.getNameSumNumberByOrderId(orderIdList);

        for (OrderSum orderSum : orderSumList) {
            nameList.add(orderSum.getName());
            numberList.add(orderSum.getTotalNumber());
        }

        return new SalesTop10ReportVO(
                StringUtil.join(",",nameList),
                StringUtil.join(",",numberList));
    }

    /**
     * 导出报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //导入xlsm模板
        try {
             InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook ex = new XSSFWorkbook(is);
           //准备数据
            LocalDate start = LocalDate.now().plusDays(-30);
            LocalDate end = LocalDate.now().plusDays(-1);
           BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
      //处理时间数据
             XSSFSheet sheet = ex.getSheet("Sheet1");
             XSSFRow row = sheet.getRow(1);
             row.getCell(1).setCellValue("从"+start.toString()+"到"+end.toString());
            //获得第4行
             row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = start.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //游览器导出数据
             ServletOutputStream outputStream = response.getOutputStream();
             ex.write(outputStream);

             //关闭资源
            outputStream.flush();
            outputStream.close();
            is.close();
            ex.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
